package com.nk.iexam.ds;

import java.util.ArrayList;
import java.util.List;

import com.nk.iexam.IExamApplication;
import com.nk.iexam.models.IModel;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public abstract class AbstractObjectDataSource<T extends IModel> 
{
	public static final String ID = "ID";
	protected String _tableName;
	protected SQLiteDatabase _database;
	protected List<String> _allColumnsName = new ArrayList<String>();
		
	public AbstractObjectDataSource()
	{
		_database = IExamApplication.getDB();
		_allColumnsName.add(ID);
	}
	
	public String[] getAllTableColumnsName()
	{
		String result[] = new String[_allColumnsName.size()];
		return _allColumnsName.toArray(result);
	}
	
	abstract protected T cursorToObject(final Cursor cursor_);
	
	public int delete(final T object_)
	{
		long id = object_.getId();
		return _database.delete(_tableName, ID + " = " + id, null);
	}
	
	public T getObjectById(final long id_) 
	{
		T result = null;
		
		//result = (T) class_.newInstance();
		Cursor cursor = _database.query(_tableName, getAllTableColumnsName(), "ID = " + id_, null, null, null, null);

		cursor.moveToFirst();
		if (!cursor.isAfterLast()) {
			result = (T) cursorToObject(cursor);
		}

		cursor.close();
		
		return result;
	}
	
	public List<T> selectObjects(String selection_)
	{
		List<T> dbObjects = new ArrayList<T>();
		Cursor cursor = _database.query(_tableName, getAllTableColumnsName(), selection_, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			T dbObject = cursorToObject(cursor);
			dbObjects.add(dbObject);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return dbObjects;
	}
	
	public List<T> getAllDbObjects()
	{
		List<T> dbObjects = new ArrayList<T>();
		Cursor cursor = _database.query(_tableName, getAllTableColumnsName(), null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			T dbObject = cursorToObject(cursor);
			dbObjects.add(dbObject);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return dbObjects;
	}
}
